import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';
import '../../../core/models/hot_item.dart';
import '../../../core/providers/hot_item_provider.dart';
import '../../community/pages/community_detail_page.dart';

/// 他人用户内容类型
enum OtherUserContentType { works, likes }

/// 他人用户内容展示组件
class OtherUserContentDisplay extends StatelessWidget {
  final String userId;
  final OtherUserContentType contentType;

  const OtherUserContentDisplay({
    super.key,
    required this.userId,
    required this.contentType,
  });

  @override
  Widget build(BuildContext context) {
    return Consumer<HotItemProvider>(
      builder: (context, hotItemProvider, child) {
        // 获取用户相关的作品数据
        final items =
            contentType == OtherUserContentType.works
                ? hotItemProvider.getUserPublishedItems(userId)
                : hotItemProvider.getUserFavoriteItems(userId);

        if (items.isEmpty) {
          return _buildEmptyContent();
        }

        return Padding(
          padding: EdgeInsets.symmetric(horizontal: 16.w),
          child: GridView.builder(
            padding: EdgeInsets.only(bottom: 100.h, top: 10.h),
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 2,
              crossAxisSpacing: 12.w,
              mainAxisSpacing: 12.h,
              childAspectRatio: 0.85,
            ),
            itemCount: items.length,
            itemBuilder: (context, index) {
              final item = items[index];
              return _buildContentCard(context, item);
            },
          ),
        );
      },
    );
  }

  /// 构建内容卡片
  Widget _buildContentCard(BuildContext context, HotItem item) {
    return GestureDetector(
      onTap: () => _navigateToDetail(context, item),
      child: Container(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(12.w),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withValues(alpha: 0.2),
              blurRadius: 8,
              offset: const Offset(0, 4),
            ),
          ],
        ),
        child: ClipRRect(
          borderRadius: BorderRadius.circular(12.w),
          child: Stack(
            fit: StackFit.expand,
            children: [
              // 背景图片
              Container(
                decoration: BoxDecoration(
                  image: DecorationImage(
                    image: _getImageProvider(item.displayImageUrl),
                    fit: BoxFit.cover,
                  ),
                ),
              ),

              // 渐变遮罩
              Container(
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    begin: Alignment.topCenter,
                    end: Alignment.bottomCenter,
                    colors: [
                      Colors.transparent,
                      Colors.black.withValues(alpha: 0.7),
                    ],
                  ),
                ),
              ),

              if (!item.isImage)
                Center(
                  child: Container(
                    width: 50.w,
                    height: 50.w,
                    decoration: BoxDecoration(
                      color: Colors.white.withValues(alpha: 0.9),
                      shape: BoxShape.circle,
                    ),
                    child: Icon(
                      Icons.play_arrow,
                      size: 30.w,
                      color: Colors.black87,
                    ),
                  ),
                ),

              // 底部信息
              Positioned(
                bottom: 12.h,
                left: 12.w,
                right: 12.w,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Text(
                      item.title,
                      style: TextStyle(
                        fontSize: 14.sp,
                        fontWeight: FontWeight.w600,
                        color: Colors.white,
                        fontFamily: 'Poppins',
                      ),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  void _navigateToDetail(BuildContext context, HotItem item) async {
    final result = await Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => CommunityDetailPage(item: item)),
    );

    // 如果返回值为 true，表示需要刷新列表
    if (result == true && context.mounted) {
      // 刷新 HotItemProvider 数据
      final hotItemProvider = context.read<HotItemProvider>();
      hotItemProvider.refresh();
    }
  }

  ImageProvider _getImageProvider(String imageUrl) {
    if (imageUrl.startsWith('http')) {
      return NetworkImage(imageUrl);
    } else if (imageUrl.startsWith('assets/')) {
      return AssetImage(imageUrl);
    } else {
      return FileImage(File(imageUrl));
    }
  }

  /// 构建空内容状态
  Widget _buildEmptyContent() {
    final isWorks = contentType == OtherUserContentType.works;

    return Builder(
      builder: (context) {
        return SingleChildScrollView(
          child: Container(
            height: MediaQuery.of(context).size.height * 0.6,
            padding: EdgeInsets.symmetric(horizontal: 20.w),
            child: Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(
                    isWorks ? Icons.music_note_outlined : Icons.favorite_border,
                    size: 80.w,
                    color: Colors.white.withValues(alpha: 0.5),
                  ),

                  SizedBox(height: 20.h),

                  Text(
                    isWorks ? 'No works yet' : 'No likes yet',
                    style: TextStyle(
                      fontSize: 18.sp,
                      color: Colors.white.withValues(alpha: 0.7),
                      fontFamily: 'Poppins',
                    ),
                  ),

                  SizedBox(height: 8.h),

                  Text(
                    isWorks
                        ? 'This user hasn\'t shared any works yet'
                        : 'This user hasn\'t liked anything yet',
                    style: TextStyle(
                      fontSize: 14.sp,
                      color: Colors.white.withValues(alpha: 0.5),
                      fontFamily: 'Poppins',
                    ),
                    textAlign: TextAlign.center,
                  ),
                ],
              ),
            ),
          ),
        );
      },
    );
  }
}
